package com.hake.core.support.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hake.core.support.web.PageParamsThreadLocal;

/**
 * 分页参数拦截器
 * @author yhaoquan
 *
 */
public class PageParamInterceptor extends HandlerInterceptorAdapter {
	
	private final Logger logger = LoggerFactory.getLogger(PageParamInterceptor.class) ;
	
	private final PathMatcher pathMatcher = new AntPathMatcher();

	/**
	 * 默认值 页码
	 */
	private Integer pageNum = 1;
	
	/**
	 * 默认值 每页显示几条
	 */
	private Integer pageSize = 30;
	
	/**
	 * 拦截的URL
	 */
	private String[] includeUrlPatterns = null;
	
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		if(isInclude(request)) {
			
			String pageNum = request.getParameter("pageNum") ;
			String pageSize = request.getParameter("pageSize") ;
			String orderBy = request.getParameter("orderBy") ;
			
			
			//将分页参数保存到ThreadLocal
			PageParamsThreadLocal.setPageNum((pageNum!=null?Integer.parseInt(pageNum):this.pageNum));
			PageParamsThreadLocal.setPageSize((pageSize!=null?Integer.parseInt(pageSize):this.pageSize));
			PageParamsThreadLocal.setOrderBy(orderBy);
			
			logger.debug("拦截到的地址：{}", request.getServletPath());
			logger.debug("设置分页参数：{}", PageParamsThreadLocal.getPageParams());
			
			return super.preHandle(request, response, handler);
        } else {
        	return super.preHandle(request, response, handler) ;
        }
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
		//清除ThradLocal中的分页参数
		PageParamsThreadLocal.removeAllPageParam();
		
		super.afterCompletion(request, response, handler, ex);
	}
	
	/**
	 * 包含URL
	 * @param request
	 * @return
	 */
	private boolean isInclude(final HttpServletRequest request) {
		if(includeUrlPatterns == null) {
			return false;
		}
		for(String pattern : includeUrlPatterns) {
			if(pathMatcher.match(pattern, request.getServletPath())) {
				return true;
			}
		}
		return false;
	}
	
	public void setIncludeUrlPatterns(String[] includeUrlPatterns) {
		this.includeUrlPatterns = includeUrlPatterns;
	}

	public void setPageNum(Integer pageNum) {
		this.pageNum = pageNum;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}
	
}
